package com.example.demo2022.interceptor;

import com.example.demo2022.common.constant.GlobalConstant;
import com.example.demo2022.entity.User;
import com.example.demo2022.util.TokenUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("AuthInterceptor preHandle....");
        String uri = request.getRequestURI();
        System.out.println("当前路径："+uri);
        /**
         * HandlerMethod=>Controller中标注@RequestMapping的方法
         *  需要配置静态资源不拦截时，添加这块逻辑  => 前后端分离项目
         *
         */
        // 是我们的conrtoller中的方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader(GlobalConstant.HEADER_TOKEN);
        User user = TokenUtil.getUser(token);
        // 一定是登陆验证成功的
       if(!user.getMenuUrlList().contains(uri)){
           throw  new RuntimeException("403 Forbidden!");
       }
        return true;
    }
}
